package listener;

import pojo.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class MyApplicationListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 1. 得到servletContext对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        // 2. 创建一个Map集合用来存放商品信息
        Map<String, Product> products = new HashMap<>();
        // 3. 构造商品列表
        Product p1 = new Product("1001", "双飞燕鼠标", 98.0f, 100);
        Product p2 = new Product("1002", "联想电脑", 3998.0f, 500);
        Product p3 = new Product("1003", "海尔洗衣机", 1200.0f, 200);
        Product p4 = new Product("1004", "海飞丝洗发水", 45.0f, 80);
        Product p5 = new Product("1005", "IPhone平板", 3000.0f, 300);
        Product p6 = new Product("1006", "焦糖瓜子", 5.0f, 200);
        // 4. 将商品放到Map集合中
        products.put(p1.getPid(),p1);
        products.put(p2.getPid(),p2);
        products.put(p3.getPid(),p3);
        products.put(p4.getPid(),p4);
        products.put(p5.getPid(),p5);
        products.put(p6.getPid(),p6);
        // 5. 将Map集合放到servletContext中
        servletContext.setAttribute("products",products);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
